package sv.com.seguros.web.controller.asg;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import sv.com.seguros.exception.WebException;
import sv.com.seguros.web.controller.BaseController;
import sv.com.seguros.web.util.DBContext;
import sv.com.seguros.web.util.WebUtilidades;

@Controller
@RequestMapping("/seguros")
public class AsgSeguroController extends BaseController {

	private static final long serialVersionUID = 3834669882649782965L;
	
	@RequestMapping(value = "/view", method = {RequestMethod.GET, RequestMethod.POST})
	public String view(ModelMap model) {
		model.put(WebUtilidades.HEADER_TITLE, "CLIENTES / POLIZAS");
		try {
			model.put("ctgAseguradoras", JSONArray.fromObject(DBContext.getCtgAseguradoraDao().findAllActivesAsArray()));
			model.put("ctgAsesores", JSONArray.fromObject(DBContext.getCtgAsesorDao().findAllActivesAsArray()));
			model.put("ctgTipoClientes", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_TIPO_SEGUROS_PADRE)));
			model.put("isReadOnly", WebUtilidades.isReadOnly(WebUtilidades.ROLE_CLIENTE_POLIZA));
		} catch (WebException e) {
			logger.error("Exception:", e);
		}
		return "aseguradora/poliza/asgDetallePoliza";
	}
	
	@RequestMapping(value = "/doSearch", method = {RequestMethod.POST})
	public void doSearch(HttpServletResponse response,
			@ModelAttribute AsgSeguroForm asgSeguroForm){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			List<Object[]> list = DBContext.getAsgClienteDao().doSearch(asgSeguroForm);
			result.put("totalResult", list.size());
			if(WebUtilidades.isEmptyList(list)) result.put("list", JSONArray.fromObject(list));
			else{
				result.put("list", JSONArray.fromObject(WebUtilidades.sublist(list, asgSeguroForm.getStart(), asgSeguroForm.getLimit())));
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		}
		serializeObject(result, response);
	}

}
